<?php

namespace App\Wechat\Remind\Jobs;

use App\Wechat\Remind\Models\Remind;
use App\Wechat\Remind\Models\Ticket;
use EasyWeChat\Factory;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class sendWxRemind implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	protected $remind;

	public $tries = 3;
	public $timeout = 120;


	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct(Remind $remind)
	{
		$this->remind = $remind;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		$config = [
			'app_id' => 'wx75882c29cb6f24fe',
			'secret' => 'ce67ed660df65a4b2b7b089609d796fd',
			'response_type' => 'array',
			'log' => [
				'level' => 'debug',
				'file' => app_path() . '/Wechat/Remind/logs/wechat.log',
			],
		];
		$app = Factory::miniProgram($config);
		$ticket = Ticket::query()->where([
			['openid', '=', $this->remind->openid],
			['is_deleted', '=', 0],
			['created_at', '>=', date('Y-m-d H:i:s', strtotime('-7 days'))]
		])
			->orderBy('created_at')
			->first(['form_id']);
		$app->template_message->send([
			'touser' => $this->remind->openid,
			'template_id' => '6lw7tBJPHrtrG2hTviloo7xUuaf1kAWxuh15Ik-Q8nQ',
			'page' => '/pages/index/timeline',
			'form_id' => $ticket->form_id,
			'data' => [
				'keyword1' => $this->remind->title,
				'keyword2' => $this->remind->date . ' '. $this->remind->time,
				'keyword3' => $this->remind->content
			]
		]);
		Ticket::query()->where('form_id', $ticket->form_id)->update(['is_deleted' => 1]);
		Remind::query()->where('id', $this->remind->id)->update(['status' => 1]);
	}
}